package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.swipelayout.SimpleSwipeListener;
import com.hjq.widget.swipelayout.SwipeLayout;
import com.hjq.widget.swipelayout.adapters.RecyclerSwipeAdapter;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.TimesBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.ThemeUtil;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.AddConditionActivity;
import com.qiantu.phone.ui.activity.EditLinkageActivity;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.utils.LinkageDataHolder;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/09/22
 * desc   : 状态数据列表
 */
public final class TimesAdapter extends RecyclerSwipeAdapter {

    private static final int TYPE_TIMES = 0x1;
    private static final int TYPE_FUTURE_TIMES_EMPTY = 0x2;
    private static final int TYPE_FUTURE_TIMES_BOTTOM_HINT = 0x3;
    private List<TimesBean> mTotalData = new ArrayList<>();//包含此刻
    private List<TimesBean> mData = new ArrayList<>();
    //不包含此刻
    private Context mContext;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    private SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private int thisMomentIndex;
    private TimesBean lastOne;
    private ViewGroup mCanHorizontalScrollParentView;

    public TimesAdapter(@NonNull Context context, ViewGroup view) {
        mContext = context;
        mCanHorizontalScrollParentView = view;
    }

    public void setData(List<TimesBean> data) {
        mData.clear();
        mData.addAll(data);
        mTotalData.clear();
        mTotalData.addAll(mData);
        notifyDatasetChanged();
    }

    //不带此刻的
    public List<TimesBean> getData() {
        return mData;
    }


    //带此刻的
    public List<TimesBean> getTotalData() {
        return mTotalData;
    }

    /**
     * 清空当前数据
     */
    public void clearData() {
        if (mTotalData == null || mTotalData.size() == 0) {
            return;
        }
        mTotalData.clear();
        notifyDataSetChanged();
    }

    @Override
    public void notifyDatasetChanged() {
        refreshCurrent();
        super.notifyDatasetChanged();
    }

    public void refreshCurrent() {
        Date current = new Date();
//        Date current = null;
//        try {
//            current = simpleDateFormat1.parse("2021-12-31 12:08:00");
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        mTotalData.clear();
        mTotalData.addAll(mData);
        //除了此刻以外的最后一个
        if(mTotalData.size() > 0){
            lastOne = mTotalData.get(mTotalData.size() - 1);
        }
        thisMomentIndex = -1;
        for (int i = 0; i < mTotalData.size(); i++) {
            TimesBean times = mTotalData.get(i);
            try {
                Date itemDate = simpleDateFormat1.parse(times.getDateTime());
                if (itemDate.before(current)) {
                    times.setTimeType(1);
                } else {
                    if (thisMomentIndex == -1) {
                        thisMomentIndex = i;
                    }
                    times.setTimeType(3);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        TimesBean timesBean = new TimesBean();
        timesBean.setTimeType(2);
        String[] ymdhm = simpleDateFormat.format(current).split(" ");
        timesBean.setDate(ymdhm[0]);
        thisMomentIndex = thisMomentIndex == -1 ? mTotalData.size() : thisMomentIndex;
        mTotalData.add(thisMomentIndex, timesBean);
    }

    @Override
    public int getItemViewType(int position) {
        if (thisMomentIndex == mTotalData.size() - 1 //此刻是集合的最后一个,那么列表最后显示空任务提示
                && position == getItemCount() - 1) {
            return TYPE_FUTURE_TIMES_EMPTY;
        } else if (position == getItemCount() - 1) {
            return TYPE_FUTURE_TIMES_BOTTOM_HINT;
        } else {
            return TYPE_TIMES;
        }
    }

    @Override
    public int getItemCount() {
        //底部会有空任务view或者只显示未来2天提示view
        return mTotalData == null ? 0 : mTotalData.size() + 1;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_FUTURE_TIMES_EMPTY:
                View emptyView = LayoutInflater.from(mContext).inflate(R.layout.item_future_empty_times, parent, false);
                emptyView.setOnClickListener(mOnClickListener);
                return new EmptyViewHolder(emptyView);
            case TYPE_FUTURE_TIMES_BOTTOM_HINT:
                return new BottomHintViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_times_bottom_hint, parent, false));
            default:
                return new ItemViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_times, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if(viewHolder instanceof BottomHintViewHolder){
            BottomHintViewHolder vh = (BottomHintViewHolder) viewHolder;
            if(getItemCount() == 1){
                vh.itemView.setVisibility(View.GONE);
            }else{
                vh.itemView.setVisibility(View.VISIBLE);
            }
        }else if (viewHolder instanceof ItemViewHolder) {
            ItemViewHolder vh = (ItemViewHolder) viewHolder;
            TimesBean lastItem = null;
            if (position > 0) {
                lastItem = mTotalData.get(position - 1);
            }
            TimesBean item = mTotalData.get(position);
            vh.tvTypeName.setText(item.getTitle());
            if (item.getContent() != null && item.getContent().size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (String string : item.getContent()) {
                    sb.append(string).append("、");
                }
                vh.tvFutureActionName.setText(sb.substring(0, sb.length() - 1));
                vh.tvPastActionName.setText(sb.substring(0, sb.length() - 1));
            }
            vh.swipeLayout.setCanHorizontalScrollParentView(mCanHorizontalScrollParentView);
            vh.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
                @Override
                public void onOpen(SwipeLayout layout) {
                    viewHolder.setIsRecyclable(false);
                }

                @Override
                public void onClose(SwipeLayout layout) {
                    viewHolder.setIsRecyclable(true);
                }
            });
            if(item.getTaskType() == 3){
                GlideApp.with(vh.icon).load(BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + item.getLogo() + "_on.png").into(vh.icon);
            }else if(item.getTaskType() == 1 || item.getTaskType() == 2 || item.getTaskType() == 7){
                int imageRes = AppApplication.getInstance().getResourceId(item.getLogo(), "attr");
                vh.icon.setImageDrawable(AppApplication.getInstance().getThemeDrawable(imageRes));
//                GlideApp.with(vh.icon).load(BuildConfig.APP_SCENE_BASE + ThemeUtil.getIconThemeSuffix() + item.getLogo() + ".png").into(vh.icon);
            }else{
                GlideApp.with(vh.icon).load(BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + item.getLogo() + ".png").into(vh.icon);
            }
            vh.itemLayout.setTag(position);
            vh.itemLayout.setOnClickListener(mOnClickListener);
            vh.btnDelete.setTag(position);
            vh.btnDelete.setOnClickListener(mOnClickListener);
            mItemManger.bind(viewHolder.itemView, position);//实现只展现一条列表项的侧滑区域
            vh.tvTimeDay.setText(item.getDate());
            vh.tvPastTimeHour.setText(item.getTime());
            if (item.getExecutionState() == 1) {//执行成功
                vh.tvPastTimeHour.setSelected(true);
            } else {
                vh.tvPastTimeHour.setSelected(false);
            }
            vh.dayBottomSpace.setVisibility(View.GONE);
            vh.thisMomentFlag.setVisibility(View.GONE);
            if (lastItem != null && lastItem.getDate().equals(item.getDate())) {
                vh.tvTimeDay.setVisibility(View.GONE);
                vh.dot.setVisibility(View.GONE);
            } else {
                vh.tvTimeDay.setVisibility(View.VISIBLE);
                vh.dot.setVisibility(View.VISIBLE);
            }
            switch (item.getTimeType()) {
                case 1:
                    //显示过去时刻的view
                    vh.pastTimesLayout.setVisibility(View.VISIBLE);

                    //隐藏未来时刻的view
                    vh.futureHourTopLine.setVisibility(View.GONE);
                    vh.futureTimeHourLayout.setVisibility(View.GONE);
                    vh.futureHourBottomLine.setVisibility(View.GONE);
                    vh.futureContentView.setVisibility(View.GONE);
                    vh.lastFutureContentViewSpace.setVisibility(View.GONE);
                    break;
                case 2:
                    //显示此刻
                    vh.dot.setVisibility(View.VISIBLE);
                    vh.thisMomentFlag.setVisibility(View.VISIBLE);
                    //如果此刻日期显示的话，需要加大此刻和日期的间隔
                    if (vh.tvTimeDay.getVisibility() == View.VISIBLE) {
                        vh.dayBottomSpace.setVisibility(View.VISIBLE);
                    } else {
                        vh.dayBottomSpace.setVisibility(View.GONE);
                    }

                    //隐藏过去时刻的view
                    vh.pastTimesLayout.setVisibility(View.GONE);
                    if(position == mTotalData.size() - 1){
                        //隐藏未来时刻的view
                        vh.futureHourTopLine.setVisibility(View.GONE);
                    }else{
                        vh.futureHourTopLine.setVisibility(View.VISIBLE);
                        ConstraintLayout.LayoutParams topLineCl = (ConstraintLayout.LayoutParams) vh.futureHourTopLine.getLayoutParams();
                        topLineCl.height = vh.futureHourTopLine.getResources().getDimensionPixelSize(R.dimen.dp_13);
                    }
                    vh.futureTimeHourLayout.setVisibility(View.GONE);
                    vh.futureHourBottomLine.setVisibility(View.GONE);
                    vh.futureContentView.setVisibility(View.GONE);
                    vh.lastFutureContentViewSpace.setVisibility(View.GONE);
                    break;
                case 3:
                    //隐藏过去时刻的view
                    vh.pastTimesLayout.setVisibility(View.GONE);

                    //显示未来时刻的view
                    vh.futureHourTopLine.setVisibility(View.VISIBLE);
                    vh.futureTimeHourLayout.setVisibility(View.VISIBLE);
                    vh.futureHourBottomLine.setVisibility(View.VISIBLE);
                    vh.futureContentView.setVisibility(View.VISIBLE);

                    /*判断未来时刻的时分是否相同*/
                    ConstraintLayout.LayoutParams topLineCl = (ConstraintLayout.LayoutParams) vh.futureHourTopLine.getLayoutParams();
                    ConstraintLayout.LayoutParams bottomLineCl = (ConstraintLayout.LayoutParams) vh.futureHourBottomLine.getLayoutParams();
                    ConstraintLayout.LayoutParams contentViewCl = (ConstraintLayout.LayoutParams) vh.futureContentView.getLayoutParams();
                    if ((lastItem != null && lastItem.getDate().equals(item.getDate()))
                            && (lastItem != null && lastItem.getTime().equals(item.getTime()))) {
                        vh.futureTimeHourLayout.setVisibility(View.INVISIBLE);
                        bottomLineCl.topToBottom = R.id.future_hour_top_line;
                        contentViewCl.topToBottom = R.id.future_hour_top_line;
                        topLineCl.height = vh.futureHourTopLine.getResources().getDimensionPixelSize(R.dimen.dp_4);
                        //和最有一个时分相同就不显示上下线
                        if (lastOne.getDate().equals(item.getDate())
                                && lastOne.getTime().equals(item.getTime())) {
                            vh.futureHourTopLine.setVisibility(View.INVISIBLE);
                            vh.futureHourBottomLine.setVisibility(View.GONE);
                            vh.lastFutureContentViewSpace.setVisibility(View.GONE);
                        }else{
                            vh.lastFutureContentViewSpace.setVisibility(View.GONE);
                        }
                    } else {
                        vh.futureTimeHourLayout.setVisibility(View.VISIBLE);
                        vh.tvFutureTimeHour.setText(item.getTime());
                        bottomLineCl.topToBottom = R.id.future_time_hour_layout;
                        contentViewCl.topToBottom = ConstraintLayout.LayoutParams.UNSET;
                        contentViewCl.topToTop = R.id.future_time_hour_layout;
                        topLineCl.height = vh.futureHourTopLine.getResources().getDimensionPixelSize(R.dimen.dp_13);
                        //日期时分不相同，但是和最后一个相同就不显示下线
                        if (lastOne.getDate().equals(item.getDate())
                                && lastOne.getTime().equals(item.getTime())) {
                            vh.futureHourBottomLine.setVisibility(View.GONE);
                            vh.lastFutureContentViewSpace.setVisibility(View.GONE);
                        }else{
                            vh.lastFutureContentViewSpace.setVisibility(View.GONE);
                        }
                    }/*判断未来时刻的时分是否相同*/
                    break;
            }
        }
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe_layout;
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = 0;
            switch (v.getId()) {
                case R.id.btn_delete:
                    position = (int) v.getTag();
                    showDeleteHintDialog(position);
                    break;
                case R.id.item_layout:
                    position = (int) v.getTag();
                    if (mItemManger.isOpen(position)) {
                        mItemManger.closeItem(position);
                    }else{
                        TimesBean timesBean = mTotalData.get(position);
                        if(!TextUtils.isEmpty(timesBean.getExecutionSerialNo())){
                            getLinkageAndToEditLinkage(timesBean.getExecutionSerialNo());
                        }
                    }
                    break;
                case R.id.btn_add_times:
                    Intent intent = new Intent(mContext, AddConditionActivity.class);
                    intent.putExtra("type", AddConditionActivity.TYPE_SCENE_LINKAGE);
                    mContext.startActivity(intent);
                    break;
            }
        }
    };

    private void getLinkageAndToEditLinkage(String linkageSerialNo){
        LLHttpManager.getLinkage((LifecycleOwner) mContext, linkageSerialNo, new HttpCallback<HttpData<LinkageBean>>(null) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<LinkageBean> result) {
                LinkageBean linkage = result.getData();
                LinkageDataHolder.setLinkageData(linkage);
                Intent intent = new Intent(mContext, EditLinkageActivity.class);
                mContext.startActivity(intent);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showDeleteHintDialog(int position) {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(mContext);
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                LLHttpManager.deleteTimeRecord((LifecycleOwner) mContext, mTotalData.get(position).getTimeRecordSerialNo(), new HttpCallback<HttpData<Void>>(null){
                    @Override
                    public void onStart(Call call) {
                        if(mContext instanceof AppActivity){
                            ((AppActivity)mContext).showDialog();
                        }
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        super.onSucceed(result);
                        ToastUtils.show(R.string.delete_success);
                        mTotalData.remove(position);
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }

                    @Override
                    public void onEnd(Call call) {
                        if(mContext instanceof AppActivity){
                            ((AppActivity)mContext).hideDialog();
                        }
                    }
                });
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(mContext.getString(R.string.delete_time_hint));
        mConfirmCancelHintDialog.show();
    }

    @Override
    public long getItemId(int position) {
        return mTotalData.get(position).hashCode();
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {

        public SwipeLayout swipeLayout;
        public View itemLayout;
        public ImageView btnDelete;
        public ImageView icon;
        public TextView tvTimeDay;
        public View dayBottomSpace;
        public View dot;
        public View thisMomentFlag;
        public TextView tvFutureTimeHour;
        public View futureTimeHourLayout;
        public View futureContentView;
        public View lastFutureContentViewSpace;
        public TextView tvTypeName;
        public TextView tvFutureActionName;
        public View futureHourTopLine;
        public View futureHourBottomLine;
        public TextView tvTime;
        public View pastTimesLayout;
        public TextView tvPastTimeHour;
        public TextView tvPastActionName;

        public ItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            swipeLayout = itemView.findViewById(R.id.swipe_layout);
            itemLayout = itemView.findViewById(R.id.item_layout);
            btnDelete = itemView.findViewById(R.id.btn_delete);
            icon = itemView.findViewById(R.id.icon);
            tvTimeDay = itemView.findViewById(R.id.tv_time_day);
            dayBottomSpace = itemView.findViewById(R.id.day_bottom_space);
            dot = itemView.findViewById(R.id.dot);
            thisMomentFlag = itemView.findViewById(R.id.this_moment_flag);
            tvFutureTimeHour = itemView.findViewById(R.id.tv_future_time_hour);
            futureTimeHourLayout = itemView.findViewById(R.id.future_time_hour_layout);
            futureContentView = itemView.findViewById(R.id.future_content_view);
            lastFutureContentViewSpace = itemView.findViewById(R.id.last_future_content_view_space);
            tvTypeName = itemView.findViewById(R.id.tv_type_name);
            tvFutureActionName = itemView.findViewById(R.id.tv_future_action_name);
            futureHourTopLine = itemView.findViewById(R.id.future_hour_top_line);
            futureHourBottomLine = itemView.findViewById(R.id.future_hour_bottom_line);
            tvTime = itemView.findViewById(R.id.tv_time);
            pastTimesLayout = itemView.findViewById(R.id.past_times_layout);
            tvPastTimeHour = itemView.findViewById(R.id.tv_past_time_hour);
            tvPastActionName = itemView.findViewById(R.id.tv_past_action_name);
        }
    }

    class EmptyViewHolder extends RecyclerView.ViewHolder {

        public EmptyViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
        }
    }

    class BottomHintViewHolder extends RecyclerView.ViewHolder {

        public BottomHintViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
        }
    }
}